import copy
import datetime
import json
import os
import traceback

from django.conf import settings
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from rest_framework.response import Response
from rest_framework.decorators import APIView

from pets import models
from pets.api.detectlogs import create_log
from pets.api.serializer import UploadImgSerializer
from predict_deploy.my_detect import start_predict
from tools.decorators import get_request_ip
from tools.tool import get_time_to_file_name, get_file_type, bytes_2_bs64


@method_decorator(get_request_ip, name='dispatch')
class UploadImg(APIView):
    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = request.data
            # print(request.FILES.get('file'))
            print(body)
            file = body.get('img')
            # print(file)
            if file:
                img_file = file.read()
                # images = copy.copy(img_file)
                name = get_time_to_file_name()
                fname, ftype = get_file_type(str(file))
                file_path = '/{}/{}'.format('upload', name+ftype)
                open_path = settings.MEDIA_ROOT + file_path
                with open(open_path, 'wb') as f:
                    f.write(img_file)

                img = img_file
                # print(img)
                # print(type(img))
                detect_path = '/{}/{}'.format('detect', name + ftype)
                save_path = settings.MEDIA_ROOT + detect_path
                ret_li, _ = start_predict(img, save_path)

                # ret_img_bs64 = bytes_2_bs64(ret_bytes)

                body['path'] = file_path
                body['n_path'] = detect_path
                ser = UploadImgSerializer(data=body)

                # print(ser.is_valid())
                if ser.is_valid():
                    ser.save()
                    # print(ser.data['id'])
                    ip = kwargs.get('req_ip')
                    data = {'name': '上传图片', 'result': json.dumps(ret_li), 'im_id': ser.data['id'], 'ip': ip}
                    create_log(data)

                    resp = {"code": 1, "data": ret_li, 'img_data': ser.data}
        except Exception as e:
            print(traceback.format_exc())
        return Response(resp)

    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = request.data
            img_id = body.get('id')
            models.UploadImg.objects.filter(id=img_id).update(
                is_acc=1
            )
            resp = {"code": 1, "data": li, 'msg': '提交成功'}
        except Exception as e:
            print(traceback.format_exc())
        return Response(resp)
